import { orderAddressAPI } from '../../utils/api';

Page({
  data: {
    orderId: '',
    consigneeName: '',
    phoneNumber: '',
    province: '',
    city: '',
    district: '',
    detailAddress: '',
    remarks: '',
    deliveryTime: '',
    loading: false
  },

  onLoad: function(options) {
    console.log('订单地址页面加载，接收到的参数:', options);
    
    // 从支付成功页面接收订单ID
    if (options.orderId) {
      this.setData({
        orderId: options.orderId
      });
    }
  },

  // 输入姓名
  onNameInput: function(e) {
    this.setData({
      consigneeName: e.detail.value
    });
  },

  // 输入手机号
  onPhoneInput: function(e) {
    this.setData({
      phoneNumber: e.detail.value
    });
  },

  // 输入详细地址
  onDetailAddressInput: function(e) {
    this.setData({
      detailAddress: e.detail.value
    });
  },

  // 输入备注
  onRemarksInput: function(e) {
    this.setData({
      remarks: e.detail.value
    });
  },

  // 选择省市区
  chooseRegion: function() {
    // 直接提示用户在详细地址中手动输入完整地址信息
    wx.showModal({
      title: '提示',
      content: '请在详细地址中填写完整的省市区及详细地址信息',
      showCancel: false
    });
  },

  // 选择上门时间
  chooseDeliveryTime: function() {
    // 使用操作菜单提供预设的时间段选项，兼容性更好
    const now = new Date();
    const today = new Date();
    const tomorrow = new Date(today);
    tomorrow.setDate(tomorrow.getDate() + 1);
    const dayAfterTomorrow = new Date(today);
    dayAfterTomorrow.setDate(dayAfterTomorrow.getDate() + 2);
    
    // 格式化日期显示
    const formatDate = (date) => {
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      const day = date.getDate();
      return `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`;
    };
    
    // 生成时间选项
    const timeOptions = [];
    const todayStr = formatDate(today);
    const tomorrowStr = formatDate(tomorrow);
    const dayAfterTomorrowStr = formatDate(dayAfterTomorrow);
    
    // 今天的时间段（从当前时间后1小时开始）
    let startHour = now.getHours() + 1;
    if (startHour >= 20) {
      // 如果当前时间已经很晚，直接显示明天的选项
      timeOptions.push(`${tomorrowStr} 09:00-12:00`);
      timeOptions.push(`${tomorrowStr} 13:00-17:00`);
      timeOptions.push(`${tomorrowStr} 18:00-20:00`);
      timeOptions.push(`${dayAfterTomorrowStr} 09:00-12:00`);
      timeOptions.push(`${dayAfterTomorrowStr} 13:00-17:00`);
    } else {
      // 今天还有可选时间段
      timeOptions.push(`${todayStr} ${startHour < 10 ? '0' + startHour : startHour}:00-12:00`);
      timeOptions.push(`${todayStr} 13:00-17:00`);
      timeOptions.push(`${todayStr} 18:00-20:00`);
      timeOptions.push(`${tomorrowStr} 09:00-12:00`);
      timeOptions.push(`${tomorrowStr} 13:00-17:00`);
      timeOptions.push(`${tomorrowStr} 18:00-20:00`);
    }
    
    wx.showActionSheet({
      itemList: timeOptions,
      success: (res) => {
        if (!res.cancel) {
          const selectedTime = timeOptions[res.tapIndex];
          this.setData({
            deliveryTime: selectedTime
          });
          console.log('选择上门时间成功:', selectedTime);
        }
      },
      fail: (err) => {
        console.error('选择上门时间失败:', err);
      }
    });
  },

  // 提交上门地址信息
  saveAddress: async function() {
    // 表单验证
    if (!this.data.consigneeName) {
      wx.showToast({
        title: '请输入收货人姓名',
        icon: 'none'
      });
      return;
    }

    if (!this.data.phoneNumber) {
      wx.showToast({
        title: '请输入手机号码',
        icon: 'none'
      });
      return;
    }

    if (!this.data.detailAddress) {
      wx.showToast({
        title: '请输入详细地址',
        icon: 'none'
      });
      return;
    }

    if (!this.data.deliveryTime) {
      wx.showToast({
        title: '请选择上门时间',
        icon: 'none'
      });
      return;
    }

    this.setData({ loading: true });

    // 构建地址数据
    const addressData = {
      orderId: this.data.orderId,
      consigneeName: this.data.consigneeName,
      phoneNumber: this.data.phoneNumber,
      province: this.data.province,
      city: this.data.city,
      district: this.data.district,
      detailAddress: this.data.detailAddress,
      remarks: this.data.remarks,
      deliveryTime: this.data.deliveryTime
    };

    console.log('提交的上门地址信息:', addressData);

    try {
      // 调用实际的API保存地址
      const result = await orderAddressAPI.saveOrderAddress(addressData);
      
      // 隐藏加载状态
      this.setData({ loading: false });
      
      if (success) {
        // 跳转到地址提交成功页面
        wx.navigateTo({
          url: '/pages/address-success/address-success'
        });
      } else {
        wx.showToast({
          title: result?.message || '地址提交失败',
          icon: 'none'
        });
      }
    } catch (error) {
      this.setData({ loading: false });
      console.error('提交地址API调用失败:', error);
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'none'
      });
    }
  },

  // 返回上一页
  goBack: function() {
    wx.navigateBack();
  }
});